//
// Created by 12992 on 24-10-23.
//

#include "process.hpp"
#include "video_meta.h"

#include <glog/logging.h>

namespace utils
{
    process::process(video_meta& meta,  callback func)
        :  func(std::move(func)), total_frames(meta.get_total_frame())
    {
        this->func(this->muxer);
    }

    void process::start_process()
    {
        std::lock_guard guard(this->status_lock);
        this->future = std::async(
            std::launch::async,
            [this]()
            {
                try
                {
                    if(this->muxer->start_mux())
                    {
                        std::lock_guard guard2(this->status_lock);
                        this->current_status = status::DONE;
                    }
                }
                catch (const std::exception& e)
                {
                    std::lock_guard lock(this->status_lock);
                    std::lock_guard lock2(this->err_msg_lock);
                    this->error_message = e.what();
                    this->current_status = status::ERROR;
                }
            });
        if (this->current_status == status::NONE)
            this->current_status = status::RUNNING;
    }

    void process::continue_process()
    {
        std::lock_guard guard(this->status_lock);
        this->future = std::async(
            std::launch::async,
            [this]()
            {
                try
                {
                    if(this->muxer->continue_mux())
                    {
                        std::lock_guard guard2(this->status_lock);
                        this->current_status = status::DONE;
                    }
                }
                catch (const std::exception& e)
                {
                    std::lock_guard lock(this->status_lock);
                    std::lock_guard lock2(this->err_msg_lock);
                    this->error_message = e.what();
                    this->current_status = status::ERROR;
                }
            });
        if (this->current_status == status::PAUSE)
            this->current_status = status::RUNNING;
    }

    void process::pause_process()
    {
        std::lock_guard guard(this->status_lock);
        this->muxer->pause_mux();
        if (this->current_status == status::RUNNING)
        {
            this->current_status = status::PAUSE;
            LOG(INFO) << "process pause";
        }
    }

    process::status process::get_status() const
    {
        std::lock_guard guard(this->status_lock);
        return this->current_status;
    }

    std::string process::get_error() const
    {
        std::lock_guard guard(this->err_msg_lock);
        return this->error_message;
    }

    int process::get_current_frame() const
    {
        return this->muxer->current_frames();
    }

    int process::get_total_frames() const
    {
        return this->total_frames;
    }
} // utils
